<template>
    <div class="app-container">
        <el-form :model="formData" ref="formData" :inline="true" label-width="100px">
            <el-form-item label="申请单标题" prop="applyTitle">
                <el-input
                        v-model="formData.applyTitle"
                        placeholder="请输入申请单标注名"
                        size="small"/>
            </el-form-item>
            <el-form-item label="发起人" prop="applyUser">
                <el-input
                        v-model="formData.applyUser"
                        readonly
                        size="small"/>
            </el-form-item>
            <el-form-item label="发起人姓名" prop="applyUserName">
                <el-input
                        v-model="formData.applyUserName"
                        readonly
                        size="small"/>
            </el-form-item>
            <el-form-item label="所属部门" prop="deptName">
                <el-input
                        v-model="formData.deptName"
                        readonly
                        size="small"/>
            </el-form-item>
            <el-form-item label="发起人岗位" prop="posts">
                <el-input readonly size="small" v-model="formData.posts">
                </el-input>
            </el-form-item>
            <el-form-item label="发起人角色" prop="roles">
                <el-input
                        v-model="formData.roles"
                        readonly
                        size="small"/>
            </el-form-item>
            <el-form-item label="发起时间" prop="createTime">
                <el-input
                        v-model="formData.createTime"
                        readonly
                        size="small"/>
            </el-form-item>
            <el-form-item label="预计总开销" prop="totalPrice">
                <el-input
                        v-model="formData.totalPrice + '元'"
                        readonly
                        size="small">
                </el-input>
            </el-form-item>
            <el-form-item label="申请单编号" prop="purApplyId">
                <el-input
                        v-model="formData.purApplyId"
                        readonly
                        size="small">
                </el-input>
            </el-form-item>
        </el-form>
        <el-table border :data="formData.purApplyGoodsBillVoList">
            <el-table-column label="序号" align="center" type="index" width="60"/>
            <el-table-column label="货品编号" align="center" prop="goodsId" :show-overflow-tooltip="true"/>
            <el-table-column label="货品名称" align="center" prop="goodsName" :show-overflow-tooltip="true"/>
            <el-table-column label="采购数量" align="center" prop="goodsNumber" width="80"/>
            <el-table-column label="用途说明" align="center" prop="usedDes" :show-overflow-tooltip="true"/>
            <el-table-column label="预计开销（元）" align="center" prop="totalPrice" :show-overflow-tooltip="true"/>
            <el-table-column label="预计存放仓库" align="center" prop="storeName" :show-overflow-tooltip="true"/>
            <el-table-column label="紧迫状态" align="center" prop="urgentStatus" :show-overflow-tooltip="true"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row,scope.$index)"
                    >修改
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row,scope.$index)"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-row type="flex" justify="center" class="mt10">
            <el-button
                    type="primary"
                    icon="el-icon-plus"
                    @click="handleAdd"
            >新增采购记录
            </el-button>
            <el-button
                    type="success"
                    icon="el-icon-refresh"
                    @click="clearGoodsList"
            >清除所有记录
            </el-button>
            <el-button
                    type="warning"
                    icon="el-icon-edit"
                    :loading="submitLoading"
                    @click="submitApplyBill"
            >保存申请单
            </el-button>
        </el-row>

        <!-- 添加或修改货品信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="goodsForm" :rules="rules" label-width="120px">
                <el-form-item label="货品编码" prop="goodsId">
                    <el-input v-model="goodsForm.goodsId" placeholder="请查询货品编码" readonly>
                        <el-button slot="append" icon="el-icon-search" @click="queryGoods">查询货品信息</el-button>
                    </el-input>
                </el-form-item>
                <el-form-item label="货品名称" prop="goodsName">
                    <el-input v-model="goodsForm.goodsName" placeholder="请查询货品名称" readonly/>
                </el-form-item>
                <el-form-item label="计量单位" prop="goodsMeasurementUnit">
                    <el-input v-model="goodsForm.goodsMeasurementUnit" placeholder="请查询计量单位" readonly/>
                </el-form-item>
                <el-form-item label="采购数量" prop="goodsNumber">
                    <el-input-number v-model="goodsForm.goodsNumber" controls-position="right" :min="0"/>
                </el-form-item>
                <el-form-item label="用途说明" prop="usedDes">
                    <el-input v-model="goodsForm.usedDes" type="textarea" placeholder="请输入用途说明"></el-input>
                </el-form-item>
                <el-form-item label="预计存放仓库" prop="storeName">
                    <el-input v-model="goodsForm.storeName" placeholder="请查询仓库名称" readonly>
                        <el-button slot="append" icon="el-icon-search" @click="queryStore">查询仓库信息</el-button>
                    </el-input>
                </el-form-item>
                <el-form-item label="期望到货时间" prop="expectGetTime">
                    <el-date-picker
                            v-model="goodsForm.expectGetTime"
                            size="small"
                            value-format="yyyy-MM-dd HH:mm:ss "
                            type="datetime"
                            placeholder="请选择日期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="紧迫程度" prop="urgentStatus">
                    <el-radio-group v-model="goodsForm.urgentStatus" size="medium">
                        <el-radio v-for="(item, index) in urgentStatusOptions" :key="index" :label="item.dictValue">
                            {{item.dictLabel}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitGoodsForm">确 定</el-button>
                <el-button @click="cancelGoodsForm">取 消</el-button>
            </div>
        </el-dialog>

        <!--查询货品信息对话框-->
        <el-dialog title="选择货品信息" :visible.sync="queryGoodsOpen" width="900px" append-to-body>
            <el-form :inline="true" :model="queryGoodsParams" ref="queryGoodsForm">
                <el-form-item label="货品名称" prop="goodsName">
                    <el-input
                            v-model="queryGoodsParams.goodsName"
                            placeholder="请输入货品名称"
                            clearable
                            size="small"
                    />
                </el-form-item>
                <el-form-item label="货品编码" prop="goodsId">
                    <el-input
                            v-model="queryGoodsParams.goodsId"
                            placeholder="请输入货品编码"
                            clearable
                            size="small"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleGoodsQuery">查询</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetForm('queryGoodsForm')">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="goodsLoading" border :data="queryGoodsList">
                <el-table-column label="货品编码" prop="goodsId" width="110"/>
                <el-table-column label="货品名称" prop="goodsName" :show-overflow-tooltip="true"/>
                <el-table-column label="货品大类" prop="goodsCategory" :formatter="goodsCategoryFormat"
                                 :show-overflow-tooltip="true"/>
                <el-table-column label="货品小类" prop="goodsType" :show-overflow-tooltip="true"/>
                <el-table-column label="计量单位" prop="goodsMeasurementUnit" align="center" width="80"/>
                <el-table-column label="货品描述" prop="goodsDes" :show-overflow-tooltip="true"/>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-edit"
                                @click="checkGoods(scope.row)"
                        >选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                    v-show="goodsTotal>0"
                    :total="goodsTotal"
                    :page.sync="queryGoodsParams.pageNum"
                    :limit.sync="queryGoodsParams.pageSize"
                    @pagination="handleGoodsQuery"
            />
            <div slot="footer" class="dialog-footer">
                <el-button @click="queryGoodsCancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择仓库信息" :visible.sync="queryStoreOpen" width="900px" append-to-body>
            <el-form :model="queryStoreParams" ref="queryStoreForm" :inline="true" label-width="68px">
                <el-form-item label="仓库名称" prop="storeName">
                    <el-input
                            v-model="queryStoreParams.storeName"
                            placeholder="请输入仓库名称"
                            clearable
                            size="small"
                    />
                </el-form-item>
                <el-form-item label="公司名称" prop="companyName">
                    <el-input
                            v-model="queryStoreParams.companyName"
                            placeholder="请输入公司名称"
                            clearable
                            size="small"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleStoreQuery">查询</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetForm('queryStoreForm')">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="storeLoading" border :data="storeList">
                <el-table-column label="序号" align="center" type="index" width="60"/>
                <el-table-column label="仓库名称" align="center" prop="storeName" :show-overflow-tooltip="true"/>
                <el-table-column label="所属公司" align="center" prop="companyName" :show-overflow-tooltip="true"/>
                <el-table-column label="所在城市" align="center" prop="storeCity" width="100"/>
                <el-table-column label="具体地址" align="center" prop="storeAddress" :show-overflow-tooltip="true"/>
                <el-table-column label="使用率" align="center" prop="storeUtilizationRate" width="80">
                    <template slot-scope="scope">
                        <span>{{scope.row.storeUtilizationRate}}%</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-edit"
                                @click="checkStore(scope.row)"
                        >选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                    v-show="storeTotal>0"
                    :total="storeTotal"
                    :page.sync="queryStoreParams.pageNum"
                    :limit.sync="queryStoreParams.pageSize"
                    @pagination="handleStoreQuery"
            />
            <div slot="footer" class="dialog-footer">
                <el-button @click="queryStoreCancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {listStore} from "@/api/store/store.js";
    import {listGoods} from "@/api/goods/goods.js";
    import {queryUserInfo,addApplyBill} from "@/api/purchase/apply.js";

    export default {
        name: "addApplyBill",
        data() {
            return {
                // 表单参数
                formData: {
                    purApplyId: undefined,
                    applyTitle: undefined,
                    applyUser: undefined,
                    applyUserName: undefined,
                    createTime: undefined,
                    applyTime: undefined,
                    approvalStatus: undefined,
                    approvalTime: undefined,
                    deptName: undefined,
                    deptId: undefined,
                    posts: undefined,
                    roles: undefined,
                    totalPrice: 0,
                    // 货品表格数据
                    purApplyGoodsBillVoList: [],
                },
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                goodsForm: {
                    goodsId: undefined,
                    goodsName: undefined,
                    goodsNumber: 50,
                    goodsMeasurementUnit: undefined,
                    goodsPrice: undefined,
                    goodsCategory: undefined,
                    goodsType: undefined,
                    usedDes: undefined,
                    storeEntityId: undefined,
                    storeName: undefined,
                    expectGetTime: undefined,
                    urgentStatus: '紧迫',
                    totalPrice: 0
                },
                urgentStatusOptions: [],
                // 表单校验
                rules: {
                    goodsId: [{
                        required: true,
                        message: '请查询货品名称',
                        trigger: 'blur'
                    }],
                    goodsName: [{
                        required: true,
                        message: '请查询货品名称',
                        trigger: 'blur'
                    }],
                    goodsMeasurementUnit: [{
                        required: true,
                        message: '请查询计量单位',
                        trigger: 'blur'
                    }],
                    goodsNumber: [{
                        required: true,
                        message: '请输入采购数量',
                        trigger: 'blur'
                    }],
                    usedDes: [{
                        required: true,
                        message: '请输入用途描述',
                        trigger: 'blur'
                    }],
                    storeName: [{
                        required: true,
                        message: '请查询预计存放仓库',
                        trigger: 'blur'
                    }]
                },
                queryGoodsOpen: false,
                queryGoodsParams: {
                    pageNum: 1,
                    pageSize: 10,
                    goodsName: undefined,
                    goodsId: undefined
                },
                goodsTotal: 0,
                goodsLoading: false,
                queryGoodsList: [],
                queryStoreOpen: false,
                queryStoreParams: {
                    pageNum: 1,
                    pageSize: 10,
                    storeName: undefined,
                    companyName: undefined
                },
                storeLoading: false,
                storeList: [],
                storeTotal: 0,
                goodsCategoryOptions: [],
                optionFlag: "add",
                optionIndex: undefined,
                submitLoading: false
            };
        },
        created() {
            let app = this;
            //获取当前操作者的信息
            queryUserInfo().then(response => {
                if (response.code === 200) {
                    app.formData.applyUser = response.data.applyUser;
                    app.formData.applyUserName = response.data.applyUserName;
                    app.formData.createTime = this.getCurrentTime();
                    app.formData.deptName = response.data.deptName;
                    app.formData.deptId = response.data.deptId;
                    var postsString = "";
                    if (response.data.posts != null && response.data.posts.length > 0) {
                        for (var i = 0; i < response.data.posts.length; i++) {
                            if (i == response.data.posts.length - 1) {
                                postsString = postsString + response.data.posts[i].postName;
                            } else {
                                postsString = postsString + response.data.posts[i].postName + ";"
                            }
                        }
                    }
                    app.formData.posts = postsString;
                    var rolesString = "";
                    if (response.data.roles != null && response.data.roles.length > 0) {
                        for (var i = 0; i < response.data.roles.length; i++) {
                            if (i == response.data.roles.length - 1) {
                                rolesString = rolesString + response.data.roles[i].roleName;
                            } else {
                                rolesString = rolesString + response.data.roles[i].roleName + ";"
                            }
                        }
                    }
                    app.formData.roles = rolesString;
                } else {
                    app.msgError(response.msg);
                }

                //获取数据字典信息
                app.getDicts("apply_goods_urgent_status").then(response => {
                    app.urgentStatusOptions = response.data;
                });

                app.getDicts("goods_info_goods_category").then(response => {
                    app.goodsCategoryOptions = response.data;
                });
            });
        },
        methods: {
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.title = "新增采购货品信息";
                this.optionFlag = "add";
                this.open = true;
            },
            reset() {
                this.goodsForm = {
                    goodsId: undefined,
                    goodsName: undefined,
                    goodsNumber: 50,
                    goodsMeasurementUnit: undefined,
                    goodsPrice: undefined,
                    goodsCategory: undefined,
                    goodsType: undefined,
                    usedDes: undefined,
                    storeEntityId: undefined,
                    storeName: undefined,
                    expectGetTime: undefined,
                    urgentStatus: '紧迫',
                    totalPrice: 0
                };
                this.resetForm("form");
            },
            cancelGoodsForm() {
                this.open = false;
            },
            queryGoods() {
                this.queryGoodsOpen = true;
            },
            handleGoodsQuery() {
                this.goodsLoading = true;
                listGoods(this.queryGoodsParams).then(
                    response => {
                        this.queryGoodsList = response.rows;
                        this.goodsTotal = response.total;
                        this.goodsLoading = false;
                    }
                );
            },
            queryGoodsCancel() {
                this.queryGoodsOpen = false;
            },
            checkGoods(row) {
                this.goodsForm.goodsId = row.goodsId;
                this.goodsForm.goodsName = row.goodsName;
                this.goodsForm.goodsMeasurementUnit = row.goodsMeasurementUnit;
                this.goodsForm.goodsPrice = row.goodsPrice;
                this.goodsForm.goodsCategory = row.goodsCategory;
                this.goodsForm.goodsType = row.goodsType;
                this.queryGoodsOpen = false;
            },
            queryStore() {
                this.queryStoreOpen = true;
            },
            handleStoreQuery() {
                this.storeLoading = true;
                listStore(this.queryStoreParams).then(response => {
                    this.storeList = response.rows;
                    this.storeTotal = response.total;
                    this.storeLoading = false;
                });
            },
            queryStoreCancel() {
                this.queryStoreOpen = false;
            },
            checkStore(row) {
                this.goodsForm.storeName = row.storeName;
                this.goodsForm.storeEntityId = row.storeEntityId;
                this.queryStoreOpen = false;
            },
            goodsCategoryFormat(row) {
                return this.selectDictLabel(this.goodsCategoryOptions, row.goodsCategory);
            },
            submitGoodsForm() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.goodsForm.totalPrice = this.goodsForm.goodsPrice*this.goodsForm.goodsNumber;
                        var goodsItem = Object.assign({}, this.goodsForm);
                        if(this.optionFlag == 'add'){
                            this.formData.purApplyGoodsBillVoList.push(goodsItem);
                            this.formData.totalPrice = this.formData.totalPrice + goodsItem.totalPrice;
                        }else{
                            this.formData.totalPrice = this.formData.totalPrice + goodsItem.totalPrice - this.formData.purApplyGoodsBillVoList[this.optionIndex].totalPrice;
                            Object.assign(this.formData.purApplyGoodsBillVoList[this.optionIndex],goodsItem);
                        }
                        this.reset();
                        this.open = false;
                    }
                })
            },
            handleDelete(row,index) {
                let app = this;
                app.$confirm('是否确认删除该采购信息?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    //移除指定索引的数组元素
                    app.formData.purApplyGoodsBillVoList.splice(index,1);
                    app.formData.totalPrice = app.formData.totalPrice - row.totalPrice;
                });
            },
            handleUpdate(row,index){
                this.goodsForm = Object.assign({},row);
                this.optionIndex = index;
                this.title = "修改采购货品信息";
                this.optionFlag = "modify";
                this.open = true;
            },
            clearGoodsList(){
                let app = this;
                app.$confirm('确认要清除所有采购信息？', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    //移除指定索引的数组元素
                    app.formData.purApplyGoodsBillVoList=[];
                    app.formData.totalPrice = 0;
                    app.formData.purApplyId = undefined;
                });
            },
            submitApplyBill(){
                this.submitLoading = true;
                if(this.formData.applyTitle == undefined || this.formData.applyTitle == "" || this.formData.applyTitle == null){
                    this.msgError("采购申请单标题必填！");
                    return;
                }
                addApplyBill(this.formData).then(response => {
                    if (response.code === 200) {
                        this.formData.purApplyId = response.data.purApplyId;
                        this.msgSuccess("保存成功,采购申请单编号为："+this.formData.purApplyId +"!");
                    } else {
                        this.msgError(response.msg);
                    }
                });
                this.submitLoading = false;
            }
        }
    };
</script>
<style>

</style>


